package app

import (
	"fmt"
	sldefine "gitee.com/simplexyz/simplego/log"
	sutil "gitee.com/simplexyz/simplego/util"
	"sync"

	"github.com/spf13/viper"

	sactor "gitee.com/simplexyz/simplego/actor"
	sadefine "gitee.com/simplexyz/simplego/actor/define"
	sahttpreq "gitee.com/simplexyz/simplego/actor/http/request"
	sahttpsvr "gitee.com/simplexyz/simplego/actor/http/server"
	satimer "gitee.com/simplexyz/simplego/actor/timer"
)

type App struct {
	config *viper.Viper

	startedWg sync.WaitGroup
	stoppedWg sync.WaitGroup

	pid            *sadefine.PID
	logger         sldefine.ILogger
	timerMgr       *satimer.Manager
	httpRequestMgr *sahttpreq.Manager
	httpServer     *sahttpsvr.Server
}

func Create(configPath string) (*App, error) {
	a := &App{
		config: viper.New(),
	}

	// todo 加载配置
	a.config.SetConfigName(sutil.MustGetProgramFileBaseName())
	a.config.SetConfigType("json")
	a.config.AddConfigPath(configPath)
	err := a.config.ReadInConfig()
	if err != nil {
		return nil, fmt.Errorf("read config file fail, %w", err)
	}

	return a, nil
}

func (a *App) WaitForStopped() {
	a.stoppedWg.Wait()
}

func (a *App) onStarted(ctx sadefine.Context) {
	a.pid = ctx.Self().Clone()
	a.logger = sactor.GetLogger(ctx, true)
	a.timerMgr = sactor.GetTimerManager(ctx)
	a.httpRequestMgr = sahttpreq.NewManager(sactor.RootContext(), a.pid, a.logger)

	// todo 根据配置文件决定要不要启动http server
}

func (a *App) onStopped(ctx sadefine.Context) {
}
